package com.snail.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.snail.config.RabbitConfig;
import com.snail.model.pojo.mall.BizOrder;
import com.snail.model.pojo.mall.BizOrderDetail;
import com.snail.model.pojo.mall.CreateOrderRequest;
import com.snail.model.pojo.mall.StockDecreaseRequest;
import com.snail.service.BizOrderDetailService;
import com.snail.service.IBizOrderService;
import com.snail.service.IBizProductService;
import com.snail.service.serviceImp.BuyOrderImp;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class BizOrderController {

    @Autowired
    private IBizOrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private BuyOrderImp buyOrderImp;
    @Autowired
    private BizOrderDetailService orderDetailService;

    @Autowired
    private IBizProductService productService;

    // Add a new order
    @PostMapping("/add")
    public boolean addOrder(@RequestBody CreateOrderRequest request) {
//        System.out.println("befire");
        System.out.println(request);
        BizOrder order = request.getOrder();
        List<StockDecreaseRequest> stockDecreaseRequests = request.getStockDecreaseRequests();
        boolean flag=buyOrderImp.createOrder(order.getUserId(),stockDecreaseRequests);
        if (flag) {

            boolean saved = orderService.save(order);

//        System.out.println("ymh+h+515");
//            System.out.println(saved);
//        System.out.println("y5615641565");
            if (saved) {
                // 发送订单号到延迟队列，24小时后处理
            System.out.println(order.getOrderNo()+"before加入队列");
                rabbitTemplate.convertAndSend(
                        RabbitConfig.ORDER_DELAY_EXCHANGE,
                        RabbitConfig.ORDER_DELAY_ROUTING_KEY,
                        order.getOrderNo()
                );
            System.out.println(order.getOrderNo()+"after加入队列");
            }
            return saved;
        }
       else {
           return false;
        }
    }
//    boolean flag=  orderService.remove(queryWrapper);
//        System.out.println(flag);
//        return flag;
    // 新增：根据订单号删除订单
@DeleteMapping("/deleteByOrderNo/{orderNo}")
@Transactional(rollbackFor = Exception.class)
public boolean deleteOrderByOrderNo(@PathVariable String orderNo) {
    try {
        // 1. 查询订单详情
        List<BizOrderDetail> orderDetails = orderDetailService.getDetailsByOrderNo(orderNo);

        if (orderDetails != null && !orderDetails.isEmpty()) {
            // 2. 恢复商品库存
            for (BizOrderDetail detail : orderDetails) {
                if (detail.getProductId() != null && detail.getQuantity() != null) {
                    // 调用增加库存方法
                    productService.increaseStock(
                            detail.getProductId().intValue(),
                            detail.getQuantity()
                    );
                    System.out.println("恢复商品 " + detail.getProductId() + " 库存 " + detail.getQuantity() + " 件");
                }
            }
        }

        // 3. 删除订单详情
        QueryWrapper<BizOrderDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("order_no", orderNo);
        orderDetailService.remove(detailQueryWrapper);
        System.out.println("删除订单详情完成");

        // 4. 删除主订单
        QueryWrapper<BizOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no", orderNo);
        boolean orderDeleted = orderService.remove(orderQueryWrapper);

        if (orderDeleted) {
            System.out.println("成功删除订单: " + orderNo);
        } else {
            System.out.println("删除订单失败: " + orderNo);
        }

        return orderDeleted;

    } catch (Exception e) {
        System.out.println("删除订单时发生错误: " + e.getMessage());
        e.printStackTrace();
        throw new RuntimeException("删除订单失败", e);
    }
}
    // Delete an order by ID
    @DeleteMapping("/deleteorder/{id}")
    public boolean deleteOrder(@PathVariable Long id) {

        return orderService.removeById(id);
    }

    // Update an order
    @PutMapping("/update")
    public boolean updateOrder(@RequestBody BizOrder order) {
        return orderService.updateById(order);
    }

    // Get order by ID
    @GetMapping("/searchbyid/{id}")
    public BizOrder getOrderById(@PathVariable Long id) {
        return orderService.getById(id);
    }

    // Get all orders
    @GetMapping("/getall")
    public List<BizOrder> getAllOrders() {
        return orderService.list();
    }

    // Get orders by pagination
    @GetMapping("/page")
    public Page<BizOrder> getOrdersByPage(@RequestParam(defaultValue = "1") Integer current,
                                          @RequestParam(defaultValue = "10") Integer size) {
        return orderService.page(new Page<>(current, size));
    }

    // Get orders by user ID
    @GetMapping("/user/{userId}")
    public List<BizOrder> getOrdersByUserId(@PathVariable Long userId) {
        QueryWrapper<BizOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return orderService.list(queryWrapper);
    }
}
